package com.lj.universalframework.http

import android.text.TextUtils
import android.util.Log
import com.lj.universalframework.utils.Utils
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import okhttp3.internal.http.StatusLine
import okio.Buffer
import java.net.HttpURLConnection
import java.nio.charset.Charset

/**
 * <p>文件名：LoggingInterceptor
 * <p>创建者：LJ
 * <p>创建日期：2020\10\15 0015 11:15  50
 * <p>描述：网络拦截器
 */
class LoggingInterceptor : Interceptor {
    private val UTF8: Charset = Charset.forName("UTF-8")

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val requestBody = request.body

        var body: String?=null
        if (requestBody != null) {

            val buffer = Buffer()
            requestBody.writeTo(buffer)

            var charset = UTF8
            val contentType = requestBody.contentType()
            charset = contentType!!.charset(UTF8)!!
            body = buffer.readString(charset)
        }

        val response = chain.proceed(request)
        val responseBody = response.body

        var rBody: String?=null
        if (hasBody(request, response)) {
            val source = responseBody!!.source()
            source.request(Long.MAX_VALUE)
            val buffer = source.buffer

            var charset = UTF8
            val contentType = responseBody.contentType()
            charset = contentType!!.charset(UTF8)!!
            rBody = buffer.clone().readString(charset)
        }


        val stringBuilder = StringBuilder()
        stringBuilder.append("{\"状态码\":\"${response.code}\",")
        if (!TextUtils.isEmpty(response.request.url.toString())) {
            stringBuilder.append("\"请求url\":\"${response.request.url}\",")
        }
        if (!TextUtils.isEmpty(body)) {
            stringBuilder.append("\"请求参数\":\"$body\",")
        }
        if (!TextUtils.isEmpty(rBody)) {
            stringBuilder.append("\"响应内容\":$rBody")
        }
        stringBuilder.append("}")
        Log.i("测试一下",stringBuilder.toString())
        Utils.logJson(stringBuilder.toString())
        return response
    }


    private fun hasBody(request: Request, response: Response): Boolean {
        // 不管响应头是什么，HEAD请求都不会产生主体。
        if (response.request.method == "HEAD") {
            return false
        }
        val responseCode = response.code
        if ((responseCode < StatusLine.HTTP_CONTINUE || responseCode >= 200)
            && responseCode != HttpURLConnection.HTTP_NO_CONTENT && responseCode != HttpURLConnection.HTTP_NOT_MODIFIED
        ) {
            return true
        }
        return stringToLong(request.headers["Content-Length"]) != -1L || "chunked".equals(
            response.header(
                "Transfer-Encoding"
            ), ignoreCase = true
        )
    }

    private fun stringToLong(s: String?): Long {
        if (s == null){
            return -1
        }
        return try {
            s.toLong()
        }catch (e: NumberFormatException){
            -1
        }
    }
}